package server;

import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;

import communication.ClientComm;
import communication.ComandoComm;
import communication.ServerComm;

public class ServerCommRMI extends UnicastRemoteObject implements ServerComm {	
	private static final long serialVersionUID = 1L;
	private Server server;
	private ArrayList<ClientComm> connections;

	public ServerCommRMI(Server s) throws RemoteException {
		connections = new ArrayList<ClientComm>();
		server = s;
		try {
			LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
			Naming.rebind("rmi://127.0.0.1/server:1999",(Remote)this);
			System.out.println("Server Avviato!");
        } catch (Exception e) {
            System.err.println("ServerCommRMI exception:");
            e.printStackTrace();
        }
	}
	
	@Override
	public void cambioTurno(String username) throws RemoteException {
		for (int i = 0; i<connections.size(); i++){
			connections.get(i).msgFromServer(ComandoComm.cambioTurno.toString() + "," + username);
		}
	}

	@Override
	public void connect(ClientComm cl) throws RemoteException {
		connections.add(cl);
	}

	@Override
	public void msgFromClient(String msg) throws RemoteException {
		new MsgInterpreter(this, server, msg);
	}

	@Override
	public void msgToClient(String msg) throws RemoteException {
		connections.get(0).msgFromServer(msg);
	}

	@Override
	public void close() throws RemoteException {
		// TODO Auto-generated method stub

	}

	@Override
	public void closeAll() throws RemoteException {
		// TODO Auto-generated method stub

	}

}
